import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

function AddForm({ orderId, modal, onSubmit, onCancel }) {
  const { ccOrderStore: store } = useStore();
  const [order, setOrder] = useState({});
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(order, name, value);
    setOrder({ ...order });

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = () => {
    onSubmit?.(order);
  };

  return (
    <Form
      inline
      value={order}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={order}
        mode={modal[0]}
        fields={['orderNumber', 'ccOrder.orderStatus', 'company.name', 'crDate',
          'ccOrder.passengerName', 'ccOrder.passengerPhone', 'ccOrder.subscribeName',
          'currency',
          'price']}
      />

      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form >
  );
}

export default AddForm;

